package net.jiastudy.biz.sys.service.impl;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;

import net.jiastudy.biz.sys.entity.Setting;
import net.jiastudy.biz.sys.mapper.SettingMapper;
import net.jiastudy.biz.sys.service.SettingService;
import net.jiastudy.biz.sys.util.SettingGroup;
import net.jiastudy.core.base.BaseService;

@Service
public class SettingServiceImpl extends BaseService<SettingMapper, Setting> implements SettingService {

	@Override
	public Setting save(SettingGroup group, Object value) {
		if (null == value) {
			return null;
		}
		Setting set = this.get(group);
		if (null != set) {
			set.setValue(JSON.toJSONString(value));
			this.updateById(set);
		} else {
			set = new Setting();
			set.setCode(group.name());
			set.setValue(JSON.toJSONString(value));
			this.insert(set);
		}
		return set;
	}

	@Override
	public Setting get(SettingGroup group) {
		EntityWrapper<Setting> ew = new EntityWrapper<>();
		ew.eq("code", group.name());
		return this.selectOne(ew);
	}

	@Override
	public <T> T get(SettingGroup group, Class<T> clazz) {
		Setting setting = this.get(group);
		if (null == setting) {
			return null;
		}
		return JSON.parseObject(setting.getValue(), clazz);
	}
}